import {useLocation, useNavigate, useOutletContext} from "react-router-dom"
import {useEffect, useState} from "react"
import Address from "./address"
import ItemInfo from "./item-info"
import {creatOrder} from "../../request/order"
import {message} from "antd"

function CreateOrder() {
    const [setTitle] = useOutletContext()
    useEffect(() => setTitle('创建订单'), [setTitle])
    const navigate = useNavigate()
    const [note, setNote] = useState('')
    const {items} = useLocation().state

    if (!items || !items.length) {
        return
    }

    const totalPrice = items
        .map(item => item.optionPrice * item.number)
        .reduce((total, value) => total + value)

    function submit() {
        creatOrder(items, totalPrice, note).then(orderId => {
            message.success('订单创建成功')
            navigate('/purchase/pay', { state: {orderId}})
        }).catch(({msg}) => message.error(msg))
    }

    return (
        <>
            <Address />
            <div className="split-line"></div>
            <b className="row">商品信息</b>
            {items.map((item, i) => (
                <ItemInfo key={i} {...item}/>
            ))}
            <div className="row prop">
                <span>商品合计</span>
                <span>￥{totalPrice}</span>
            </div>
            <div className="row prop">
                <span>运费</span>
                <span>￥0</span>
            </div>
            <div className="row prop">
                <span>备注</span>
                <input placeholder="请输入备注信息"
                       value={note}
                       onChange={e => setNote(e.target.value)}>
                </input>
            </div>
            <div className="blank"></div>
            <div className="submit-container">
                <div>实付款</div>
                <div className="price">￥{totalPrice}</div>
                <div className="blank"></div>
                <div className="submit-btn" onClick={submit}>提交订单</div>
            </div>
        </>
    )
}

export default CreateOrder